#!/bin/bash

set -euo pipefail

TIMEOUT_SECONDS=10

TARGETS=(qemu-sifive-e31 qemu-sifive-s51 qemu-sifive-u54 qemu-sifive-u54mc )
PROGRAMS=(hello minimal-boot )

for target in ${TARGETS[@]} ; do
    for program in ${PROGRAMS[@]} ; do

        build_output_file=$( mktemp -p ./ tmp.${target}.${program}.build.XXXXXXXXXX)
        run_output_file=$( mktemp -p ./ tmp.${target}.${program}.run.XXXXXXXXXX)

        case $program in
            hello)              expected_output="Hello, World!";;
            minimal-boot)       expected_output="minimal-boot";;
            *)                  expected_output="";;
        esac

        >&2 echo "Building ${program} on ${target}"

        make TARGET=${target} PROGRAM=${program} 2>&1 | tee ${build_output_file}

        >&2 echo "Running ${program} on ${target}"

        timeout --foreground ${TIMEOUT_SECONDS}s bash -c "make TARGET=${target} PROGRAM=${program} simulate 2>/dev/null | tee ${run_output_file}"

        if [ ! -f ${run_output_file} -o `cat ${run_output_file} | grep -c "${expected_output}"` -eq 0 ] ; then
            >&2 echo "${program} on ${target} failed to produce the expected output"
        else
            >&2 echo "${program} on ${target} passed"
        fi

        # Make sure we clean up after ourselves
        make TARGET=${target} PROGRAM=${program} clean 2>&1 >/dev/null
    done
done

>&2 echo "All tests passed on QEMU"
